//
//  PatternShap.m
//  QuartzStudy
//
//  Created by longhuihu on 11-6-21.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PatternShape.h"

#define PSIZE 16    // size of the pattern cell

static void MyDrawStencilStar (void *info, CGContextRef myContext)
{
    int k;
    double r, theta;
	
    r = 0.8 * PSIZE / 2;
    theta = 2 * M_PI * (2.0 / 5.0); // 144 degrees
	
    CGContextTranslateCTM (myContext, PSIZE/2, PSIZE/2);
	
    CGContextMoveToPoint(myContext, 0, r);
    for (k = 1; k < 5; k++) {
        CGContextAddLineToPoint (myContext,
								 r * sin(k * theta),
								 r * cos(k * theta));
    }
    CGContextClosePath(myContext);
    CGContextFillPath(myContext);
}

@implementation PatternShape


- (void)drawRect:(CGRect)rect
{
	CGContextRef context = UIGraphicsGetCurrentContext();
	CGRect bounds = self.bounds;
	
	CGPatternRef pattern;
    CGColorSpaceRef baseSpace;
    CGColorSpaceRef patternSpace;
    static const float color[4] = { 0, 1, 0, 1 };// 1
    static const CGPatternCallbacks callbacks = {0, &MyDrawStencilStar, NULL};// 2
	
    baseSpace = CGColorSpaceCreateDeviceRGB ();// 3
    patternSpace = CGColorSpaceCreatePattern (baseSpace);// 4
    CGContextSetFillColorSpace (context, patternSpace);// 5
    CGColorSpaceRelease (patternSpace);
    CGColorSpaceRelease (baseSpace);
    pattern = CGPatternCreate(NULL, CGRectMake(0, 0, PSIZE, PSIZE),// 6
							  CGAffineTransformIdentity, PSIZE, PSIZE,
							  kCGPatternTilingConstantSpacing,
							  false, &callbacks);
    CGContextSetFillPattern (context, pattern, color);// 7
    CGPatternRelease (pattern);// 8
    CGContextFillRect (context,bounds);
}

@end
